import axios from 'axios'
import router from '../router'
import cookieUtil from '../util/cookie'

axios.defaults.baseURL = "/api/"
const http = axios.create()

//拦截器
http.interceptors.request.use(config => {
  console.log("请求拦截");
  if(config.url.startsWith("/user/login")){
    return config
  }
  //携带token
  let token = cookieUtil.getCookie("authorization")
  let refresh = cookieUtil.getCookie("Refreshtoken")
  if(token){
    config.headers.Authorization = token
  }

  if(refresh){
    config.headers.Refreshtoken = refresh
  }
  return config
})

http.interceptors.response.use(response => {
  if(response.data.code == 403){
    router.push("/login")
  }
  if(response.data.code == 401){
    router.push("/main/noperms")
  }
  console.log("响应拦截");
  // 获取token refreshtoken 如果有则放到cookie中
  let token = response.headers.authorization
  let refreshtoken = response.headers.refreshtoken

  //判断是否有值
  if(token){
    document.cookie = "authorization=" + token;
  }      
  if(refreshtoken){
    document.cookie = "Refreshtoken=" + refreshtoken;
  }
  return response
})


export default http